<template>
    <div v-if="isOpen" ref="menuRef"
        class="absolute bg-white border border-gray-200 rounded shadow-lg z-50 min-w-[120px]"
        :style="{ left: `${x}px`, top: `${y}px` }" @click.away="closeMenu">
        <ul class="py-1">
            <li v-for="(item, index) in menuItems" :key="index"
                class="px-4 py-2 hover:bg-gray-100 cursor-pointer flex items-center"
                @click="handleMenuItemClick(item.action)">
                <i :class="item.icon" class="mr-2 text-gray-600"></i>
                <span>{{ item.label }}</span>
            </li>
        </ul>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
    isOpen: {
        type: Boolean,
        default: false
    },
    x: {
        type: Number,
        default: 0
    },
    y: {
        type: Number,
        default: 0
    },
    node: {
        type: Object,
        default: null
    }
})

const emit = defineEmits(['close', 'action'])

const menuItems = ref([])
const menuRef = ref(null) // 新增：菜单DOM引用

// 新增：点击外部关闭菜单
const handleClickOutside = (event) => {
    if (menuRef.value && !menuRef.value.contains(event.target)) {
        closeMenu()
    }
}


// 根据节点类型设置菜单项
watch(() => props.node, (node) => {
    if (!node) return

    if (node.children) {
        // 文件夹菜单项
        menuItems.value = [
            { label: '新建文件夹', icon: 'fa fa-folder-o', action: 'newFolder' },
            { label: '新建文件', icon: 'fa fa-file-o', action: 'newFile' },
            { label: '重命名', icon: 'fa fa-pencil', action: 'renameFolder' },
            { label: '删除', icon: 'fa fa-trash', action: 'deleteFolder' }
        ]
    } else if (node.path.endsWith('.md')) {
        // Markdown文件菜单项
        menuItems.value = [
            { label: '重命名', icon: 'fa fa-pencil', action: 'renameFile' },
            { label: '删除', icon: 'fa fa-trash', action: 'deleteFile' }
        ]
    }
}, { immediate: true })

const closeMenu = () => {
    emit('close')
}

const handleMenuItemClick = (action) => {
    emit('action', action, props.node)
    closeMenu()
}

// 新增：生命周期钩子，绑定和解除点击事件
onMounted(() => {
    document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside)
})
</script>
